package ssm.Servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * Servlet implementation class CheckCodeServlet
 */
@WebServlet("/CheckCode")
public class CheckCodeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Random random=new Random();
	private Color getRandomColor(){
        int r=random.nextInt(256);
         int g=random.nextInt(256);
         int b=random.nextInt(256);
        return new Color(r,g,b);
     }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        BufferedImage image = new BufferedImage(90,30,BufferedImage.TYPE_INT_BGR);
        Graphics graphics = image.getGraphics();
        graphics.setColor(Color.yellow);
        graphics.fillRect(0,0,90,30);
        for (int i=0;i<5;i++){
            graphics.setColor(getRandomColor());
            int x1=random.nextInt(90);
            int y1=random.nextInt(30);
            int x2=random.nextInt(90);
            int y2=random.nextInt(30);
            graphics.drawLine(x1,y1,x2,y2);
        }
        char [] arrays={'A','B','b','D','E','e'};
        StringBuilder builder = new StringBuilder();
        for(int i=0;i<4;i++){
            int index=random.nextInt(arrays.length);
            builder.append(arrays[index]);
        }
        for (int i=0;i<builder.toString().length();i++)
        {
            graphics.setColor(getRandomColor());
            char item=builder.toString().charAt(i);
            graphics.drawString(item+"",10+(i*20),15);
        }
        request.getSession().setAttribute("checkCode",builder.toString());
        ImageIO.write(image,"png",response.getOutputStream());
     }
}
